<template>
  <div>
    <el-form
      :model="organizationForm"
      :rules="rules"
      ref="organizationForm"
      label-width="80px">
      <el-form-item
        label="分组名"
        prop="name">
        <el-input
          placeholder="请输入分组名"
          v-model="organizationForm.name">
        </el-input>
      </el-form-item>
    </el-form>
    <div align="center">
      <submit-button
        :loading="submitLoading"
        @submit="submitForm('organizationForm')"
      />
      <cancel-button @cancel="cancelSubmit" />
    </div>
  </div>
</template>

<script>
import { modifyOrganizationInfo } from '@/api/organization'
export default {
  name: 'ModifyOrganizationForm',
  props: {
    organizationInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      organizationForm: {
        id: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入分组名', trigger: 'blur' },
          { max: 20, message: '长度最多20个字符', trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  methods: {
    reset () {
      this.organizationForm.id = this.organizationInfo.organizationId
      this.organizationForm.name = this.organizationInfo.organizationName
    },
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 提交修改表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleModifyOrganizationInfo()
        } else {
          return false
        }
      })
    },
    // 修改分组信息
    async handleModifyOrganizationInfo () {
      const { id, name } = this.organizationForm
      this.submitLoading = true
      await modifyOrganizationInfo(id, name)
      this.submitLoading = false
      this.$message.success('修改分组成功')
      this.$emit('submit')
    }
  }
}
</script>
